import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login', // 这个是进行分类打包 // 如果不写 : 表示打包到一个js文件中
    // 这是路由懒加载的形式来写的
    /* webpackChunkName: "login" */ component: () =>
      import(/* webpackChunkName: "login" */ '@/views/Login')
  },
  {
    path: '/',
    name: 'Home',
    component: () => import(/* webpackChunkName: "welcome" */ '@/views/Home'),
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        name: 'Welcome',
        component: () =>
          import(/* webpackChunkName: "welcome" */ '@/views/Welcome')
      },
      {
        path: '/users',
        name: 'Users',
        component: () => import(/* webpackChunkName: "users" */ '@/views/Users')
      },
      {
        path: '/rights',
        name: 'Rights',
        component: () =>
          import(/* webpackChunkName: "rights" */ '@/views/rights/Rights')
      },
      {
        path: '/roles',
        name: 'Roles',
        component: () =>
          import(/* webpackChunkName: "roles" */ '@/views/rights/Roles')
      },
      {
        path: '/goods',
        name: 'Goods',
        component: () =>
          import(/* webpackChunkName: "goods" */ '@/views/goods/Goods')
      },
      {
        path: '/goods/add',
        name: 'Add',
        component: () =>
          import(/* webpackChunkName: "adds" */ '@/views/goods/Add')
      },
      {
        path: '/params',
        name: 'Params',
        component: () =>
          import(/* webpackChunkName: "params" */ '@/views/goods/Params')
      },
      {
        path: '/categories',
        name: 'Categories',
        component: () =>
          import(
            /* webpackChunkName: "categories" */ '@/views/goods/Categories'
          )
      },
      {
        path: '/orders',
        name: 'Orders',
        component: () =>
          import(/* webpackChunkName: "orders" */ '@/views/orders/Orders.vue')
      },
      {
        path: '/reports',
        name: 'Reports',
        component: () =>
          import(
            /* webpackChunkName: "reports" */ '@/views/reports/Reports.vue'
          )
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  // if (to.path !== '/login') {
  //   // 去的地方不是login
  //   if (token) {
  //     // 已经登录
  //     return next() // 已经登录 并且去的地方不是登录页  === 直接放行
  //   } else {
  //     return next('/login') // 没有登录 ===直接会login
  //   }
  // } else {
  //   // 去的地方不是login
  //   if (token) {
  //     // 去的地方是login  并且  有登录
  //     return next('/welcome')
  //   } else {
  //     return next()
  //   }
  // }
  // 判断有没有token  以及是不是login
  if (to.path === '/login') return next()
  if (!token) return next('/login')
  next()
})

export default router
